import Vue from 'vue';
import config from '@/config/index.js';
import moment from "moment"
import api from "../api/api.js"
const vue = new Vue;
const uviewTheme = config.uviewTheme;
export default {


	install: function(Vue, vm) {
		/**
		 * 轻提示
		 * @param {string} msg
		 */
		Vue.prototype.formRules = function(datails) {
				for (let i = 0; i < datails.list.length; i++) {
					const innerList = datails.list[i].list;
					for (let j = 0; j < innerList.length; j++) {
						const {
							required,
							key,
							name,
							type
						} = innerList[j];

						if (required) {
							datails.rules[key] = {
								'text': [{
									required: true,
									message: `请输入${name}`,
									trigger: ['change', 'blur'],
								}],
								'textarea': [{
									required: true,
									message: `请输入${name}`,
									trigger: ['change', 'blur'],
								}],
								'time': [{
									required: true,
									message: `请选择${name}`,
									trigger: ['change', 'blur'],
								}],
								'file': [{
									type: 'array',
									required: true,
									message: `请上传${name}`,
									trigger: ['change', 'blur'],
								}],
								'card': [{
									required: true,
									message: `请上传${name}`,
									trigger: ['change', 'blur'],
								}],
								'code': [{
									validator: (rule, value, callback) => {
										if (!value) {
											callback(new Error(`请选择${name}`))
											return false
										} else if (value && !value.code) {
											callback(new Error(`请输入内容`))
											return false
										} else {
											return true
										}
									},
									trigger: ['change', 'blur'],
								}]
							} [type];
						}
					}
				}
				return datails;
			},
			Vue.prototype.viewPdf = function(filePath) {
				let that = this
				wx.getSystemInfo({
					success: function(res) {
						console.log(res)
						if (res.platform == 'android') {
							uni.downloadFile({
								url: filePath,
								success: function(res) {
									var filePath = res.tempFilePath;
									uni.openDocument({
										filePath: filePath,
										success: function(res) {
											console.log("打开文档成功");
										},
									});
								},
							});
						} else {
							uni.navigateTo({
								url: `/pages/pdfView/index?urls=${filePath}`
							})
						}
					}
				})
			},
			Vue.prototype.geTel = function(tel) {
				var reg = /^(\d{3})\d{4}(\d{4})$/;
				return tel.replace(reg, "$1****$2");
			},
			Vue.prototype.unitConverter = function(num) {
				if (num) {
					num = num.toString().split("."); // 分隔小数点
					var arr = num[0].split("").reverse(); // 转换成字符数组并且倒序排列
					var res = [];
					for (var i = 0, len = arr.length; i < len; i++) {
						if (i % 3 === 0 && i !== 0) {
							res.push(","); // 添加分隔符
						}
						res.push(arr[i]);
					}
					res.reverse(); // 再次倒序成为正确的顺序

					if (num[1]) {
						if (num[1].length < 2) {
							// 如果有小数的话添加小数部分
							res = res.join("").concat("." + num[1] + '0');
						} else if (num[1].length > 2) {
							let data = num[1].substring(0, 2)
							// 如果有小数的话添加小数部分
							res = res.join("").concat("." + data);
						} else {
							res = res.join("").concat("." + num[1]);
						}

					} else {
						res = res.join("").concat("." + '00');
					}
				} else {
					res = '0.00'
				}
				return res;
			},
			Vue.prototype.getMonthList = function() {
				let monthNow = moment().month()
				let yearNow = moment().year()
				let dateList = []
				for (var y = 2023; y <= yearNow; y++) {
					dateList.push({
						value: y,
						label: y + "年",
						children: []
					})
				}
				dateList.forEach((item) => {
					if (item.value == yearNow) {
						for (var m = 0; m <= monthNow; m++) {
							item.children.push({
								value: m + 1,
								label: m + 1 + "月"
							})
						}
					} else {
						for (var m = 0; m <= 11; m++) {
							item.children.push({
								value: m + 1,
								label: m + 1 + "月"
							})
						}
					}
				})
				return dateList
			},
			Vue.prototype.getDateList = function() {
				let monthNow = moment().month()
				let yearNow = moment().year()
				let dateNow = moment().date()
				let dateList = []
				let thirtyOneDays = []
				let thirtyDays = []
				let twentyEightDays = []
				let twentyNineDays = []
				for (var d = 1; d <= 31; d++) {
					thirtyOneDays.push({
						value: d,
						label: d + '日'
					})
				}
				for (var d = 1; d <= 30; d++) {
					thirtyDays.push({
						value: d,
						label: d + '日'
					})
				}
				for (var d = 1; d <= 28; d++) {
					twentyEightDays.push({
						value: d,
						label: d + '日'
					})
				}
				for (var d = 1; d <= 29; d++) {
					twentyNineDays.push({
						value: d,
						label: d + '日'
					})
				}
				for (var y = 2000; y <= yearNow; y++) {
					dateList.push({
						value: y,
						label: y + "年",
						children: []
					})
				}
				dateList.forEach((item) => {
					var MM = 0
					if (item.value == yearNow) {
						MM = monthNow
					} else {
						MM = 11
					}
					for (var m = 0; m <= MM; m++) {
						switch (m) {
							case 0:
							case 2:
							case 4:
							case 6:
							case 7:
							case 9:
							case 11:
								item.children.push({
									value: m + 1,
									label: m + 1 + "月",
									children: thirtyOneDays
								})
								break;
							case 1:
								if (item.value % 4 == 0 && item.value % 100 != 0 || item.value % 400 ==
									0) {
									item.children.push({
										value: m + 1,
										label: m + 1 + "月",
										children: twentyNineDays
									})
								} else {
									item.children.push({
										value: m + 1,
										label: m + 1 + "月",
										children: twentyEightDays
									})
								}
								break;
							case 3:
							case 5:
							case 8:
							case 10:
								item.children.push({
									value: m + 1,
									label: m + 1 + "月",
									children: thirtyDays
								})
								break;
						}
					}
				})
				dateList.forEach((y) => {
					if (y.value == yearNow) {
						y.children.forEach((m) => {
							if (m.value == monthNow + 1) {
								let days = []
								for (var d = 1; d <= dateNow; d++) {
									days.push({
										value: d,
										label: d + '日'
									})
								}
								m.children = days
							}
						})
					}
				})

				return dateList
			},
			Vue.prototype.accMul = (arg1, arg2) => {
				// 增加浮点数的相乘方法
				var m = 0,
					s1 = arg1.toString(),
					s2 = arg2.toString();
				try {
					m += s1.split('.')[1].length;
				} catch (e) {
					// ee
				}
				try {
					m += s2.split('.')[1].length;
				} catch (e) {
					//e
				}
				return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m);
			},
			Vue.prototype.accSub = function(arg1, arg2) {
				var r1, r2, m, n;
				try {
					r1 = arg1.toString().split(".")[1].length
				} catch (e) {
					r1 = 0
				}
				try {
					r2 = arg2.toString().split(".")[1].length
				} catch (e) {
					r2 = 0
				}
				m = Math.pow(10, Math.max(r1, r2));
				//last modify by deeka
				//动态控制精度长度
				n = (r1 >= r2) ? r1 : r2;
				return ((this.accMul(arg1, m) - this.accMul(arg2, m)) / (m * 1.0)).toFixed(n);
			},
			Vue.prototype.commonAdd = function(arg1, arg2) {
				let r1, r2, m, n
				try {
					r1 = arg1.toString().split('.')[1].length;
				} catch (e) {
					r1 = 0;
				}
				try {
					r2 = arg2.toString().split('.')[1].length;
				} catch (e) {
					r2 = 0;
				}
				m = Math.pow(10, Math.max(r1, r2));
				n = r1 >= r2 ? r1 : r2
				return +((arg1 * m + arg2 * m) / m).toFixed(n)
			}

		Vue.prototype.$toast = function(msg, obj) {
			if (obj) {
				try {
					obj.$refs.uToast.show({
						title: msg
					});
				} catch (err) {
					uni.showToast({
						title: msg,
						icon: "none"
					})
				};
			} else {
				uni.showToast({
					title: msg,
					icon: "none"
				})
			}
		}
		/**
		 * 获取主题名称
		 */
		Vue.prototype.themeName = () => {
			return uni.getStorageSync('themeName') ? uni.getStorageSync('themeName') : 'primary';
		}
		/**
		 * 获取主题颜色
		 */
		Vue.prototype.themeColorValue = (type = uni.getStorageSync('themeName') ? uni.getStorageSync(
					'themeName') :
				'primary') => {
				return uviewTheme[type] ? uviewTheme[type] : uviewTheme.primary;
			},

			/**
			 * 获取主题颜色的rgba颜色值
			 * @param {Object} opacity 0-1
			 */
			Vue.prototype.themeRgba = function(opacity = 1) {
				let type = uni.getStorageSync('themeName') ? uni.getStorageSync('themeName') : 'primary';
				let rgb = vue.$u.hexToRgb(uviewTheme[type]);
				let rgba = rgb.replace(/rgb/g, 'rgba').replace(/\)/g, `, ${opacity})`);
				return rgba;
			},

			/**
			 * 拆分数组
			 */
			Vue.prototype.groupArray = (array, subGroupLength) => {
				let index = 0;
				let newArray = [];
				while (index < array.length) {
					newArray.push(array.slice(index, index += subGroupLength));
				}
				return newArray;
			}


		/**
		 * 检测是否是网络链接
		 */
		Vue.prototype.checkHttpLink = (value) => {
			if (/http/g.test(value)) {
				return true;
			} else {
				return false;
			}
		}

		/**
		 * 切分小数
		 */
		Vue.prototype.groupNumMonery = (num) => {
			let monery = (num * 1).toFixed(2);
			return monery.split('.');
		}


		/**
		 * 对象转数组
		 */
		Vue.prototype.formatObjArray = (obj) => {
			let keys = Object.keys(obj);
			let arr = [];
			keys.forEach(item => {
				arr.push({
					label: obj[item],
					value: item
				})
			});
			return arr;
		}

		/**
		 * 默认，随机颜色，传index 指定颜色，
		 */
		Vue.prototype.randomColor = (index) => {
			let colors = [
				'#02C8A5', '#e54d42', '#f37b1d', '#fbbd08', '#8dc63f', '#39b54a',
				'#1cbbb4', '#0081ff', '#6739b6', '#9c26b0', '#e03997', '#a5673f',
				'#8799a3', '#aaaaaa', '#333333', '#ff9900', '#fa3534', '#6739b6'
			];
			let i = parseInt(Math.random() * (colors.length - 0 + 1) + 0, 10);
			if (index) {
				return colors[index] ? colors[index] : colors[i];
			}
			return colors[i];
		}

		/**
		 * 获取icon，baseUrl
		 */
		Vue.prototype.getIconUrl = () => {
			let type = uni.getStorageSync('themeName') ? uni.getStorageSync('themeName') : 'primary'
			return config.iconUrl;
		}

		Vue.prototype.getTabbar = (midIndex) => {
				let url = Vue.prototype.getIconUrl();
				//midButton: midIndex === 0,
				return [{
						iconPath: `${config.iconUrl}/tool.png`,
						selectedIconPath: `${config.iconUrl}/tool-selected.png`,
						text: '工具箱',
						count: 0,
						isDot: true,
						customIcon: false,
						midButton: false,
						pagePath: "/pages/index/index"
					},
					{
						iconPath: `${config.iconUrl}/user.png`,
						selectedIconPath: `${config.iconUrl}/user-selected.png`,
						text: '我的',
						midButton: midIndex === 1,
						customIcon: false,
						midButton: false,
						pagePath: "/pages/user/index"
					},
					// {
					// 	iconPath: `${config.iconUrl}/weather.png`,
					// 	selectedIconPath: `${config.iconUrl}/weather-selected.png`,
					// 	text: '天气',
					// 	midButton: true,
					// 	customIcon: false,
					// },
					// {
					// 	iconPath: "play-right",
					// 	selectedIconPath: "play-right-fill",
					// 	text: '购物车',
					// 	midButton: midIndex === 2,
					// 	customIcon: false,
					// 	pagePath: "/pages/cart/cart"
					// },
					// {
					// 	iconPath: "account",
					// 	selectedIconPath: "account-fill",
					// 	text: '我的',
					// 	count: 0,
					// 	isDot: false,
					// 	midButton: midIndex === 3,
					// 	customIcon: false,
					// 	pagePath: "/pages/my/my"
					// },
				]
			},

			/**
			 * 登陆
			 */
			Vue.prototype.userLogin = () => {
				return new Promise((resolve, reject) => {

					if (uni.getStorageSync('token')) {
						resolve(uni.getStorageSync('user'));
					}

					uni.login({
						success(result) {
							vue.$api.login(result.code).then(res => {
								const {
									user,
									token
								} = res.data
								console.log(user);
								uni.setStorageSync('token', token.accessToken);
								uni.setStorageSync('user', user);
								uni.setStorageSync('wechatOpenId', user.wxaOpenId)
								resolve(user);
							});
						}
					})
				});

			}

		Vue.prototype.timestampToDate = (timestamp, separator = '.') => {
			var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
			var Y = date.getFullYear() + separator;
			var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) +
				separator;
			var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
			// var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
			// var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
			// var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
			return Y + M + D;
		}

		Vue.prototype.timestampToDateTime = (timestamp, separator = '.') => {
			var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
			var Y = date.getFullYear() + separator;
			var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) +
				separator;
			var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
			var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
			var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
			var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
			return Y + M + D + h + m + s;
		}

		Vue.prototype.timestampToHours = (timestamp, separator = '.') => {
			var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
			// var Y = date.getFullYear() + separator;
			// var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + separator;
			// var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
			var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
			var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
			// var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
			return h + m;
		}

		Vue.prototype.doBusiness = (start, end) => {
			var date = new Date();
			var Y = date.getFullYear() + '/';
			var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) +
				'/';
			var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
			let date_day = Y + M + D;
			let start_time = new Date(date_day + start).getTime();
			let end_time = new Date(date_day + end).getTime();
			let current_time = date.getTime()

			if (current_time > start_time && current_time < end_time) {
				return true;
			}
			return false;
		}

		Vue.prototype.timePoints = (start = '8:30', end = '17:00') => {
			var date = new Date();
			var Y = date.getFullYear() + '/';
			var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) +
				'/';
			var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
			let date_day = Y + M + D;
			let starts = start.split(':');
			let ends = end.split(':');
			let arr = [];
			for (let i = starts[0] * 1; i < ends[0] * 1; i++) {
				arr.push({
					name: i + ':00'
				});
				arr.push({
					name: i + ':30'
				});
			}
			let rangeArr = [];
			let start_time = new Date(date_day + start).getTime();
			let end_time = new Date(date_day + end).getTime();
			arr.forEach(item => {
				let current_time = new Date(date_day + item.name).getTime();
				if (current_time > start_time && current_time < end_time) {
					rangeArr.push(item)
				}
			})
			return [M + D, rangeArr, Y + M + D];
		}

		Vue.prototype.getUrlParams = (url) => {
			let index = url.indexOf('?') + 1;
			let params_str = url.substr(index);
			let params_arr = params_str.split('&');
			let obj = {}
			params_arr.forEach(item => {
				let keyVal = item.split('=');
				obj[keyVal[0]] = keyVal[1];
			});
			return obj;
		}

		Vue.prototype.uploadFile = (filePath) => {
			return new Promise((resolve, reject) => {
				const header = {
					appId: uni.getStorageSync('userKey').appId,
					authorization: uni.getStorageSync('userKey').authorization,
					platform: 'seller'
				}
				uni.uploadFile({
					url: config.uploadFileUrl,
					filePath,
					header: header,
					name:'uploadFile',
					success: (res) => {
						resolve(JSON.parse(res.data));
					},
					fail: (err) => {
						reject(err);
					}
				});
			})
		}
	}
}